package com.rogerfan.easy.shiro;

import java.io.Serializable;
import java.util.Collection;
import java.util.concurrent.TimeUnit;

import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.eis.AbstractSessionDAO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

@Component
public class RedisShiroSessionDao extends AbstractSessionDAO {
	public Logger logger = LoggerFactory.getLogger(getClass());

	private String sessionprefix = "shiro-session-";
	@Autowired
	public RedisTemplate<Object, Object> redistTemplate;

	@Override
	public void update(Session session) throws UnknownSessionException {
		try {
			
			redistTemplate.opsForValue().set(session.getId().toString(),
					session, getSec(session.getTimeout()), TimeUnit.SECONDS);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}

	}

	private int getSec(long times) {
		return (new Long(times / 1000)).intValue();
	}

	@Override
	public void delete(Session session) {
		try {
			redistTemplate.delete(session.getId().toString());
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}

	}

	@Override
	public Collection<Session> getActiveSessions() {
		// String keys = sessionprefix + "*";
		// List<Session> list = null;
		// try {
		// logger.debug("取得所有的ActiveSession");
		// Set<Session>
		// allSession=redistTemplate.keys(pattern)cached.getKeys(keys);
		// if(allSession!=null)
		// list = new ArrayList<Session>(allSession);
		// } catch (Exception e) {
		// logger.error(e.getMessage(), e);
		// }
		// return list;
		return null;
	}

	@Override
	protected Serializable doCreate(Session session) {
		Serializable sessionId = session.getId();
		try {
			super.assignSessionId(session,
					sessionprefix + super.generateSessionId(session));
			update(session);
			sessionId = session.getId();
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		return sessionId;

	}

	@Override
	protected Session doReadSession(Serializable sessionId) {
		Session session = null;
		try {
			session = (Session) redistTemplate.opsForValue().get(
					sessionId.toString());
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		return session;

	}

	public String getSessionprefix() {
		return sessionprefix;
	}

	public void setSessionprefix(String sessionprefix) {
		this.sessionprefix = sessionprefix;
	}

}